package com.juc.cf;

import java.util.concurrent.*;

/**
 * @auther zzyy
 * @create 2022-01-16 16:53
 */
public class CompletableFutureUseDemo05 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {

        ExecutorService threadPool = Executors.newFixedThreadPool(3);

        try {
            CompletableFuture<Integer> cf = CompletableFuture.supplyAsync(() -> {
                System.out.println(Thread.currentThread().getName() + "----come in");
                int result = ThreadLocalRandom.current().nextInt(10);
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + " -----1秒钟后出结果：" + result);
                if (result > 5) {
                    int i = 10 / 0;
                }
                return result;
            }, threadPool).whenComplete((v, e) -> {
                if (e == null) {
                    System.out.println(Thread.currentThread().getName() + " -----计算完成，更新系统 UpdateValue：" + v);
                }
            }).exceptionally(e -> {
                System.out.println(Thread.currentThread().getName() + " 异常情况：" + e.getCause() + "\t" + e.getMessage());
                return 1;
            });

//            System.out.println(cf.get());
            System.out.println(Thread.currentThread().getName() + " 线程先去忙其它任务");

        } finally {
            threadPool.shutdown();
        }
    }
}
